package ar.edu.itba.pod.legajo47279;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {

	private static Pattern pattern;
	private static Matcher matcher;

	private static final String IPADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
			+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
			+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
			+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

	/**
	 * Validate ip address with regular expression
	 * 
	 * @param ip
	 *            ip address for validation
	 * @return true valid ip address, false invalid ip address
	 */
	public static boolean validate(final String ip) {
		pattern = Pattern.compile(IPADDRESS_PATTERN);
		matcher = pattern.matcher(ip);
		return matcher.matches();
	}
	
	public static String getLocalIP() throws UnknownHostException {
		InetAddress addr;
		String host = "";
		
		addr = InetAddress.getLocalHost();
		byte[] ipAddr = addr.getAddress();

		StringBuffer stringBuffer = new StringBuffer();
		for (int i = 0; i < 3; i++) {
			stringBuffer.append(String
					.valueOf((int) (ipAddr[i] & 0xFF)));
			stringBuffer.append(".");
		}
		stringBuffer.append(String.valueOf((int) (ipAddr[3] & 0xFF)));
		host = stringBuffer.toString();
		
		return host;
	}
}